from flask import Blueprint, request, make_response, jsonify, redirect

from app import db
from util.captcha.captcha import captcha
import json, random, time, requests,snowflake.client
from util.myredis import r
from models.user import Server,Server2,Server1,Sf_login,BaseModel,Users,Need_Label
from werkzeug.security import generate_password_hash,check_password_hash
from utils.myjwt import myjwt

label_blue = Blueprint("labelblue",__name__)

def create_servercode(tablename,count):
    # 生成唯一ID
    code = snowflake.client.get_guid()
    # 用redis解决时钟回拨，根据key查询上一次存入的结果
    # 和当前生成的进行对比，如果当前小于redis中存储的，说明发生了时钟回拨的问题
    value = r.get_str(tablename)
    if value:
        if int(code) < int(value):
            create_servercode(tablename,count)
    # 把最后一次生成的存入redis
    r.set_str(tablename,code)
    # 取模获取列表
    number = hash(code)%(count)
    if number == 0:
        return tablename,code
    else:
        return tablename + str(number),code

@label_blue.route('/get_labels')
def get_labels():
    label = Need_Label.query.all()
    lists = []
    list_one = []
    for i in label:
        list_one.append({
            'id':i.id,
            'name':i.name,
            'pid':i.pid
        })
    dict = {}
    for i in list_one:
        k = i['id']
        dict[k] = i
    for j in list_one:
        pid = j['pid']
        if pid == 0:
            lists.append(j)
        else:
            if 'son' not in dict[pid]:
                dict[pid]['son'] = []
            dict[pid]['son'].append(j)
    return jsonify({
        'code':200,
        'msg':"获取一级标签成功",
        'data':lists
    })

@label_blue.route('/add_server',methods=['POST'])
def get_label2():
    data = json.loads(request.data)
    title = data['title']
    mobile = data['mobile']
    desc = data['desc']
    label = data['label']
    money = float(data['money'])
    user_id = data['user_id']
    type = data['type']
    # 生成code,雪花算法生成code
    tablename,code = create_servercode('Server',3)
    tablename = globals().get(f'{tablename}')
    if not all([type,title,desc,label,money,user_id]):
        return jsonify({
            'code':400,
            'msg':"参数不完整"
        })
    try:
        serve = tablename(code=code,title=title,mobile=mobile,type=type,desc=desc,label=label,budget=money,user_id=user_id)
        db.session.add(serve)
        db.session.commit()
        return jsonify({
            'code':200,
            'msg':"发布需求成功"
        })
    except Exception as e:
        print(e)
        return jsonify({
            'code':400,
            'msg':"报错"
        })
@label_blue.route('/home_label')
def home_label():
    label = Need_Label.query.filter(Need_Label.pid!=0).all()
    lst = []
    for i in label:
        lst.append({
            'id':i.id,
            'name':i.name,
            'pid':i.pid
        })
    return jsonify({
        'code':200,
        'msg':"获取主页三级标签成功",
        'data':lst
    })

@label_blue.route('/server_all')
def server_all():
    page = request.args.get('page')
    page_size = request.args.get('page_size')
    print('>>>>>>>>>>',page,page_size)
    start = (int(page) - 1) * int(page_size)
    print(start)
    key = "homes" + str(page)
    server = r.get_str(key)
    if server:
        print('缓存')
        server = json.loads(server)
    else:
        flag = r.str_setnx(key + 'setnx',1)
        if flag == True:
            print('数据库')
            q1 = db.session.query(Server).filter(Server.status == 0)
            q2 = db.session.query(Server1).filter(Server1.status == 0)
            q3 = db.session.query(Server2).filter(Server2.status == 0)
            ret = q1.union(q2).union(q3).offset(start).limit(page_size).all()  # 数据重复，只留一条  # 数据重复，只留一条
            server = []
            for i in ret:
                server.append({
                    'id': str(i.code),
                    'title': i.title,
                    'user_id': i.user_id,
                    'type': i.type,
                    'desc': i.desc,
                    'label': i.label,
                    'budget': float(i.budget),
                    'mobile': i.mobile,
                    'status': i.status,
                    'create_time':str(i.create_time)
                })
            print(server)
            # 将数据存入redis当中
            r.add_str(key,json.dumps(server))
            # 释放锁
            r.del_key(key + 'setnx')
    q1 = db.session.query(Server).filter(Server.status == 0)
    q2 = db.session.query(Server1).filter(Server1.status == 0)
    q3 = db.session.query(Server2).filter(Server2.status == 0)
    total = q1.union(q2).union(q3).count()
    return jsonify({
        'code':200,
        'msg':"OK",
        'data':server,
        'total':total
    })


@label_blue.route('/label_index')
def label_index():
    input = request.args.get('input')
    page = request.args.get('page')
    page_size = request.args.get('page_size')
    start = (int(page) - 1) * int(page_size)
    end = int(start) + int(page_size)
    lst = []
    res = Server.query.filter(Server.label.ilike(f"%{input}%")).all()
    if res:
        lst.append(res)
    ress = Server1.query.filter(Server1.label.ilike(f"%{input}%")).all()
    if ress:
        lst.append(ress)
    resa = Server2.query.filter(Server2.label.ilike(f"%{input}%")).all()
    if resa:
        lst.append(resa)
    new_list = [j for i in lst for j in i]
    tow_list = []
    if new_list:
        lens = len(new_list)
        for s in new_list:
            tow_list.append({
                'id': str(s.code),
                'title': s.title,
                'user_id': s.user_id,
                'type': s.type,
                'desc': s.desc,
                'label': s.label,
                'budget': float(s.budget),
                'mobile': s.mobile,
                'status': s.status,
                'create_time':str(s.create_time)

            })

        return jsonify({
            'code': 200,
            'msg': "OK",
            'data':tow_list[start:end],
            'total':lens
        })
    else:
        return jsonify({
            'code': 400,
            'msg': "数据不存在"
        })

def a():
    q1 = db.session.query(Server).filter(Server.status == 0)
    q2 = db.session.query(Server1).filter(Server1.status == 0)
    q3 = db.session.query(Server2).filter(Server2.status == 0)
    ret = q1.union(q2).union(q3).offset(0).limit(3).all()  # 数据重复，只留一条
    rets = q1.union(q2).union(q3).count()
    print(">>>",rets)
    list = []
    for i in ret:

        list.append({
            'id': i.code,
            'title': i.title,
            'user_id': i.user_id,
            'type': i.type,
            'desc': i.desc,
            'label': i.label,
            'budget': i.budget,
            'mobile': i.mobile,
            'status': i.status,
            'create_time':i.create_time
        })
    print(list)
# a()





















